import 'dart:async';

import 'completer.dart';

// 简单的取消令牌
class CancellationToken {
  bool _isCancelled = false;
  bool get isCancelled => _isCancelled;

  void cancel() {
    _isCancelled = true;
  }
}

void executeLongRunningTask(Completer<void> completer, CancellationToken token) async {
  try {
    for (int i = 0; i < 100; i++) {
      // 在执行每一步之前检查是否已被取消
      if (token.isCancelled) {
        throw CancelledException("Task was cancelled during operation.");
      }
      // 模拟一些工作，例如文件读取、计算等
      await Future.delayed(Duration(milliseconds: 100));
      print("Processing step $i");
    }
    if (!token.isCancelled) {
      completer.complete();
      print("Task finished successfully.");
    }
  } on CancelledException catch (e) {
    if (!completer.isCompleted) {
      completer.completeError(e);
    }
  } catch (e) {
    if (!completer.isCompleted) {
      completer.completeError(e);
    }
  }
}

void main() async {
  final completer = Completer<void>();
  final cancellationToken = CancellationToken();

  // 启动任务
  executeLongRunningTask(completer, cancellationToken);

  // 模拟在1秒后取消任务
  await Future.delayed(Duration(seconds: 1));
  cancellationToken.cancel(); // 设置取消标志
  print("External cancellation requested.");

  try {
    await completer.future;
  } on CancelledException catch (e) {
    print("Main caught: $e");
  }
}